﻿using System.Windows;
using System.Windows.Controls;


namespace Test.Common
{
    public class PassWordHelper : DependencyObject
    {
        //                     DependencyProperty
        public static readonly DependencyProperty PassWordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PassWordHelper), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged)));

        static bool _isupdataing = false;
        public static string GetPassWord(DependencyObject d)
        {

            return d.GetValue(PassWordProperty).ToString();
        }

        public static void SetPassWord(DependencyObject d, string value)
        {
            d.SetValue(PassWordProperty, value);
        }
     

        //==================
        public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PassWordHelper), new FrameworkPropertyMetadata(default(bool), new PropertyChangedCallback(OnAttach)));

        public static bool GetAttach(DependencyObject d)
        {
            return (bool)d.GetValue(AttachProperty);
        }

        public static void SetAttach(DependencyObject d, bool value)
        {
            d.SetValue(AttachProperty, value);
        }


        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            password.PasswordChanged -= Password_PasswordBox;
            if (!_isupdataing)
            {
                password.Password = e.NewValue.ToString();
            }
            password.PasswordChanged += Password_PasswordBox;

        }



        private static void OnAttach(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            password.PasswordChanged += Password_PasswordBox;
        }


        private static void Password_PasswordBox(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            _isupdataing = true;
            SetPassWord(passwordBox, passwordBox.Password);
            _isupdataing = false;

        }




    }
}
